// 全局错误处理中间件
function globalErrorHandler(err, req, res, next) {
    let statusCode = err.status || 500;
    let message = err.message || '未知错误';
    let error = {
        name: err.name || 'Error',
        message: message,
    };

    // 处理 JWT 错误
    if (err.name === 'UnauthorizedError') {
        statusCode = 401;
        message = '令牌无效或缺失';
        error.name = '未授权';
        error.message = message;
    }

    res.status(statusCode).json({
        success: false,
        timestamp: new Date().toISOString(),
        message: message,
        error: error,
        data: null,
    });
}

module.exports = globalErrorHandler;